package com.ruoyi.generator.controller.ysd;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.GenMobilePage;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.service.IFromBuildConfigService;
import com.ruoyi.generator.service.IFromCrudBtnsService;
import com.ruoyi.generator.service.IFromCrudTableConfigService;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.generator.service.impl.FromBuildConfigServiceImpl;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysMenuService;
import com.zgl.youshuda.core.service.procservice.InterDealProcService;
import com.zgl.youshuda.core.utils.OperResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 平台移动端
 */
@RestController
public class YsdMobileController extends BaseController
{
    @Autowired
    private IGenTableService genTableService;
    @Autowired
    private IFromBuildConfigService fromBuildConfigService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private InterDealProcService ysdProcService;

    /**
     * 保存表单设计信息
     * @return
     */
    @PostMapping("page/gener/build/mobileSave")
    public AjaxResult saveMobileSaveBuild(@RequestBody GenMobilePage genMobilePage) throws Exception {
        return genTableService.saveMobileSaveBuild(genMobilePage);
    }

    /**
     * 获取表单设计字段配置信息
     *
     * @param confParams
     * @return
     */
    @PostMapping(value = "/common/basemode/mobile/getFormBuildConfig")
    public AjaxResult getFormBuildConfig(@RequestBody Map<String, Object> confParams) {
        if (confParams == null || confParams.size() <= 0) {
            return AjaxResult.error("操作失败，参数获取异常");
        }
        HashMap<String, Object> retMap = new HashMap<>();
        Object pageBuildConfig = fromBuildConfigService.getFormBuildConfig(confParams).get("data");
        JSONObject pageConfig = JSONObject.parseObject(JSONObject.toJSONString(pageBuildConfig));
        List<JSONObject> fieldInfos = JSONArray.parseArray(pageConfig.getString("formBuildInfo"), JSONObject.class);
        pageConfig.put("formBuildInfo", getDictDataList(fieldInfos));
        retMap.put("pageBuildConfig", pageConfig);
        /**
         * 获取页面特殊组件的数据（选择器、单选、复选等）
         */
//        retMap.put("pageDictData", getDictDataList(pageBuildConfig));

        return AjaxResult.success("成功", retMap);
    }

    /**
     * 获取页面特殊组件的数据（选择器、单选、复选等）
     * @param fieldInfos
     * @return
     */
    private List<JSONObject> getDictDataList (List<JSONObject> fieldInfos) {


        // 遍历字段，处理特殊属性
        List<String> chooseType = Arrays.asList("van-picker","van-radio","van-checkbox");
        //字典信息
        SysDictType _dictType;
        //字典配置
        HashMap<String, Object> dictConfig;
        //字典数据
        List<SysDictData> sysDictData;
        List<JSONObject> children;
        for (JSONObject fieldInfo : fieldInfos) {
            //为存在字典的字典获取对应的选项信息
            if (StringUtils.isNotEmpty(fieldInfo.getString("optionDictCode")) && chooseType.contains(fieldInfo.getString("moduleType"))) {
                dictConfig = new HashMap<>();
                //获取初始化字典信息
                sysDictData = dictTypeService.selectDictDataByType(fieldInfo.getString("optionDictCode"));
                /**
                 * 字典懒加载判断
                 */
                _dictType = dictTypeService.selectDictTypeByType(fieldInfo.getString("optionDictCode"));
                if("1".equals(_dictType.getBeLazy())){
                    ArrayList<Object> dictItemsValue = new ArrayList<>();
                    sysDictData.forEach(item -> {
                        dictItemsValue.add(item.getDictValue());
                    });
                    // 已有的字典value
                    dictConfig.put("dictItemsValue",dictItemsValue);
                    // 字段类型标识
                    dictConfig.put("dictType",_dictType.getDictType());
                }
                //懒加字典标识
                dictConfig.put("beLazy",_dictType.getBeLazy());
                //字典api
                dictConfig.put("ysdApi",_dictType.getYsdApi());
                //字典数据
                dictConfig.put("dictItems",sysDictData);
                //装入数据
                fieldInfo.put("dictData",dictConfig);
                //retMap.put(fieldInfo.getString("vModel"),dictConfig);
            }else{
                if(chooseType.contains(fieldInfo.getString("moduleType"))){
                    dictConfig = new HashMap<>();
                    //字典数据
                    dictConfig.put("dictItems",new ArrayList<>());
//                    retMap.put(fieldInfo.getString("vModel"),dictConfig );
                    fieldInfo.put("dictData",dictConfig);
                }
            }
            children = fieldInfo.getList("children", JSONObject.class);
            if(children != null && children.size()>0){
                getDictDataList(children);
            }
        }
        return fieldInfos;
    }

    /**
     * 获取移动端附件上传信息
     * @return
     */
    @GetMapping("page/gener/mobile/getFileSaveInfo/{recordId}")
    public AjaxResult getFileSaveInfo(@PathVariable String recordId,@RequestParam String businessName) {
        HashMap<String, String> params = new HashMap<>();
        params.put("recordId", recordId);
        params.put("businessName", businessName);
        OperResult operResult = ysdProcService.dealProc("TkPN246RUNH0hEKnyuk9jjcnkJzXFg6j", params);
        if(operResult.isSuccess() && operResult.getData()!=null){
            List<JSONObject> files = JSONArray.parseArray(JSONObject.toJSONString(operResult.getData()), JSONObject.class);
            files.forEach(item -> {
                item.put("url", Constants.RESOURCE_PREFIX+"/"+item.getString("url"));
            });
            return AjaxResult.success(files);
        }else{
            return AjaxResult.success(new ArrayList<>());
        }
    }
}
